package com.kongyz.demo.reentrantlocktest;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 锁中断的例子
 */
public class ReentrantLockInterrupt {
    
    static Lock lock1=new ReentrantLock();
    static Lock lock2=new ReentrantLock();

    public static void main(String[] args) {
        //该线程先获取锁1，再获取锁2
        Thread thread=new Thread(new ThreadDemo(lock1, lock2));
        //该线程先获取锁2，再获取锁1
        Thread thread2=new Thread(new ThreadDemo(lock2, lock1));
        thread.start();
        thread2.start();
        //如果没有线程中断，这两个线程将处于死锁状态，永远无法停止，
        
        //使第一个线程中断
        thread.interrupt();        
    }
    
    
    static class ThreadDemo implements Runnable{
        Lock firstLock,secendLock;

        public ThreadDemo(Lock firstLock, Lock secendLock) {
            this.firstLock = firstLock;
            this.secendLock = secendLock;
        }

        @Override
        public void run() {
            try {
                firstLock.lockInterruptibly();
                
                TimeUnit.MILLISECONDS.sleep(10);
                secendLock.lockInterruptibly();
                
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                firstLock.unlock();
                secendLock.unlock();
                System.out.println(Thread.currentThread().getName() + "正常结束");
            }
        }
    }
}
